package com.project.api.ym.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.project.api.common.Unit;
import com.project.api.ym.model.Admin;
import com.project.api.ym.model.Roles;
import com.project.api.ym.model.Rules;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Repository
public class AdminDao {
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;

    @Autowired
    private RolesDao rolesDao;



    public List<Roles> Roles(long aid){
        List<Roles> roles = new ArrayList<>();
        String sql = "SELECT * FROM "+ Admin.tableAdminRoles +" a inner join "+Roles.tableName+" b on a.roles_id=b.id where a.admin_id=?";
        try {
            roles = mainJdbcTemplate.query(
                    sql, new Object[] {aid},new BeanPropertyRowMapper(Roles.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return roles;
        }
        Iterator<Roles> iter = roles.iterator();
        while (iter.hasNext()) {
            Roles r =  iter.next();
            r.setRules(rolesDao.Rules(r.getId()));
        }
        return roles;
    }

    public List<Admin> GetAllAdmin(){
        List<Admin> admins = new ArrayList<>();
        String sql = "SELECT `name`,realname FROM "+ Admin.tableName +"  where id <> 1";
        try {
            admins = mainJdbcTemplate.query(
                    sql, new Object[] {},new BeanPropertyRowMapper(Admin.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return admins;
        }
        return admins;
    }

    public List<Admin> GetAllAdminByName(String name){
        List<Admin> admins = new ArrayList<>();
        String sql = "SELECT `name`,realname,username FROM "+ Admin.tableName +"  where id <> 1 and (`name` like '%"+name+"%' or username like '%"+name+"%')";
        try {
            admins = mainJdbcTemplate.query(
                    sql, new Object[] {},new BeanPropertyRowMapper(Admin.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return admins;
        }
        return admins;
    }

    public Admin GetAdminById(long id){
        Admin admin=new Admin();
        String sql = "Select `name`,realname,username from "+Admin.tableName+" where id="+id;
        try {
            admin = (Admin) mainJdbcTemplate.queryForObject(
                    sql, new Object[] {},new BeanPropertyRowMapper(Admin.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return admin;
        }
        if(admin != null && admin.getId()!=0L){
            admin.setRoles(this.Roles(admin.getId()));
        }
        return admin;
    }

    public long AdminCreate(JSONObject json, long creator, long updateby) throws Exception {
        String sql="insert into "+ Admin.tableName +"(username,password,avatar,mobile,`name`,realname,ctime,utime,banner) " +
                "values(?,?,?,?,?,?,?,?,?)";
        long id=0;
//        try {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        mainJdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                String username = (String) json.getOrDefault("username",null);
                if (username == null) ps.setNull(1, Types.NULL);else ps.setString(1, username);
                String password = (String) json.getOrDefault("password",null);
                if (password==null) ps.setNull(2,Types.NULL);else ps.setString(2,password);
                String avatar = (String)json.getOrDefault("avatar",null);
                if (avatar==null) ps.setNull(3,Types.NULL);else ps.setString(3,avatar);
                String mobile = (String)json.getOrDefault("mobile",null);
                if (mobile==null) ps.setNull(4,Types.NULL);else ps.setString(4,mobile);
                String name = (String)json.getOrDefault("name",null);
                if (name==null) ps.setNull(5,Types.NULL);else ps.setString(5,name);
                String realname = (String)json.getOrDefault("realname",null);
                if (realname==null) ps.setNull(6,Types.NULL);else ps.setString(6,realname);
//                    ArrayList<String> images= (ArrayList<String>) json.getOrDefault("images",new ArrayList<>());
                ps.setLong(7, (Long) json.getOrDefault("ctime",System.currentTimeMillis()));
                ps.setLong(8, (Long) json.getOrDefault("utime",System.currentTimeMillis()));
                String banner = (String)json.getOrDefault("banner",null);
                if (banner==null) ps.setNull(9,Types.NULL);else ps.setString(9,banner);
                return ps;
            }
        }, keyHolder);
        id=keyHolder.getKey().intValue();
//        } catch (Exception  e) {
//            logger.error(e.getMessage());
//            throw new Exception(e.getMessage());
//        }
        return id;
    }

    public long AdminUpdate(long id,JSONObject json){
        String sql="update "+Admin.tableName+" set username= ? , avatar=? , mobile=? , `name`=? , realname=? , " +
                "utime=? , banner=? " ;
        String password = (String) json.getOrDefault("password",null);
        if (password !=null && !password.equalsIgnoreCase("")){
            sql= sql +" , password="+"'"+password+"'";
        }
            sql= sql+" where id = ?";
        String t = (String) json.getOrDefault("username",null);
        Object username = (String) json.getOrDefault("username",null)==null?Types.NULL:t;
        String a = (String)json.getOrDefault("avatar",null);
        Object avatar = (String) json.getOrDefault("avatar",null)==null?Types.NULL:a;
        String m = (String)json.getOrDefault("mobile",null);
        Object mobile = (String) json.getOrDefault("mobile",null)==null?Types.NULL:m;
        String n = (String)json.getOrDefault("name",null);
        Object name = (String) json.getOrDefault("name",null)==null?Types.NULL:n;
        String r = (String)json.getOrDefault("realname",null);
        Object realname = (String) json.getOrDefault("realname",null)==null?Types.NULL:r;
        String b = (String)json.getOrDefault("banner",null);
        Object banner = (String) json.getOrDefault("banner",null)==null?Types.NULL:b;
        int res=mainJdbcTemplate.update(sql, username,avatar,mobile,name,realname,System.currentTimeMillis(),banner,id);
        return id;
    }
}
